# -*- coding: utf-8 -*-
import paddle.fluid as fluid
import numpy as np
import os
import sys
import paddle
import psycopg2
import pymysql

current_path = os.path.dirname(__file__)
os.chdir(current_path)
project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 获取当前文件路径的上一级目录

paddle.enable_static()


def auto_QA(question):
    noAns = "对不起，您查询的问题暂时还未收录，请您询问具体工作人员。"

    # file_path = project_path + '/dataset/FAQ.txt'  # 拼接路径字符串

    # def get_ans(i):
    #     connect = pymysql.Connect(
    #         host="192.168.8.23",
    #         port=3306,
    #         user="root",
    #         passwd="root",
    #         db="ld_qa",
    #         charset='utf8'
    #     )

    def get_ans_by_postGres(i):
        connect = psycopg2.connect(
            database="jjgj_db_23", user="postgres", password="123456", host="192.168.8.25", port="5432"
        )
        cursor = connect.cursor()
        sql = "select * from qa_fqa where id=" + str(i)
        cursor.execute(sql)
        lines = cursor.fetchall()
        cursor.close()
        connect.close()
        if len(lines) == 0:
            return noAns
        return lines[0][1]
        # with open(file_path, 'r', encoding="utf-8") as f:
        #     lines = f.readlines()
        # for line in lines:
        #     # title = line.split('\t')[0]
        #     title = line.split('|')[0]
        #     if (int(title) == i):
        #         t_ = line.split('|')[-1]
        #         # t_ = line.split('\t')[-1]
        #         return t_

    # 用训练好的模型进行预测并输出预测结果
    # 创建执行器
    place = fluid.CPUPlace()
    exe = fluid.Executor(place)
    # exe.run(fluid.default_startup_program())
    save_path = project_path + '/model/work/infer_model/'
    # save_path = 'E:/shenhaitaoPyCode/leidiQA_web/model/work/infer_model/'

    # 从模型中获取预测程序、输入数据名称列表、分类器
    [infer_program, feeded_var_names, target_var] = fluid.io.load_inference_model(dirname=save_path, executor=exe)

    # 获取数据
    def get_data(sentence):
        file_path = project_path + '/dataset/dict_txt.txt'  # 拼接路径字符串
        # 读取数据字典
        with open(file_path, 'r', encoding='utf-8') as f_data:
            dict_txt = eval(f_data.readlines()[0])
        dict_txt = dict(dict_txt)
        # 把字符串数据转换成列表数据
        keys = dict_txt.keys()
        data = []
        for s in sentence:
            # 判断是否存在未知字符
            if not s in keys:
                s = '<unk>'
            data.append(np.int64(dict_txt[s]))
        return data

    data = []
    question1 = get_data(question)
    data.append(question1)

    # 获取每句话的单词数量
    base_shape = [[len(c) for c in data]]

    # 生成预测数据
    tensor_words = fluid.create_lod_tensor(data, base_shape, place)

    # 执行预测
    result = exe.run(program=infer_program,
                     feed={feeded_var_names[0]: tensor_words},
                     fetch_list=target_var)

    # 分类名称
    # names = ['查询排名量化', '打印成绩单在读证明', '户籍证明', '七年制成绩学历证明', '证书丢失', '查试卷', '上网查成绩', '转专业', '转学', '校历', '免试研究生', '缓考',
    #          'BB平台', '教务系统', '14']

    # 获取结果概率最大的label
    for i in range(len(data)):
        lab = np.argsort(result)[0][i][-1]
        # print('预测结果标签为：%d， 名称为：%s， 概率为：%f' % (lab, names[lab], result[0][i][lab]))
        print('预测结果标签为：%d， 概率为：%f' % (lab, result[0][i][lab]))

        if result[0][i][lab] > 0.5:
            say = get_ans_by_postGres(lab)
            # say = get_ans(lab)
            return say
        else:
            return noAns


if __name__ == '__main__':
    q = sys.argv[1]
    print("问题：", q)
    qa = auto_QA(q)
    print(qa)
